<template>
  <div class="container">
    <el-card class="card_header">{{ ShowTitle }}</el-card>
    <el-card class="card_body">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!-- 学科 -->
        <el-form-item label="学科:  " prop="subjectID">
          <el-select
            v-model="form.subjectID"
            placeholder="请选择"
            style="width: 400px"
            @change="changeSub"
          >
            <el-option
              v-for="item in subject"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 目录 -->
        <el-form-item label="目录: " prop="catalogID">
          <el-select
            v-model="form.catalogID"
            placeholder="请选择"
            style="width: 400px"
          >
            <el-option
              v-for="item in catalog"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 企业 -->
        <el-form-item label="企业: " prop="enterpriseID">
          <el-select
            v-model="form.enterpriseID"
            placeholder="请选择"
            style="width: 400px"
          >
            <el-option
              v-for="item in companylist"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 城市 -->
        <el-form-item label="城市: " prop="city">
          <el-select
            v-model="form.province"
            placeholder="请选择"
            style="width: 197px; margin-right: 6px"
            @change="getcountryData"
          >
            <el-option
              v-for="item in Allcity"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
          <el-select
            v-model="form.city"
            placeholder="请选择"
            style="width: 197px"
          >
            <el-option
              v-for="item in Allcountry"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 方向 -->
        <el-form-item label="方向: " prop="direction">
          <el-select
            v-model="form.direction"
            placeholder="请选择"
            style="width: 400px"
          >
            <el-option
              v-for="item in direction"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 题型 -->
        <el-form-item label="题型: " prop="questionType">
          <el-radio-group v-model="form.questionType" @change="changeradio">
            <el-radio label="1">单选</el-radio>
            <el-radio label="2">多选</el-radio>
            <el-radio label="3">简答</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 难度 -->
        <el-form-item label="难度: " prop="difficulty">
          <el-radio-group v-model="form.difficulty">
            <el-radio label="1">简单</el-radio>
            <el-radio label="2">一般</el-radio>
            <el-radio label="3">困难</el-radio>
          </el-radio-group>
        </el-form-item>
        <!--题干 富文本编辑器 -->
        <el-form-item label="题干: " prop="question" class="articles_content">
          <quill-editor
            v-model="form.question"
            :options="editorOption"
            @blur="$refs.form.validateField('question')"
          ></quill-editor>
        </el-form-item>
        <!-- 单选多选的切换 -->
        <el-form-item v-if="ChangeBox" label="选项: " class="el_form_itemdf">
          <el-radio-group v-model="radio3">
            <el-checkbox-group v-model="checkbox">
              <div
                class="radio_checked"
                v-for="(item, index) in form.options"
                :key="index"
              >
                <el-radio v-if="ChangeRadio" :label="item.code"
                  >{{ item.code }}: &nbsp;</el-radio
                >
                <el-checkbox v-else :label="item.code"
                  >{{ item.code }}: &nbsp;</el-checkbox
                >
                <el-input style="width: 240px" v-model="item.title"></el-input>
                <el-upload
                  @click.native="ClickImg(index)"
                  class="avatar-uploader"
                  action="#"
                  :show-file-list="false"
                  :http-request="httpRequest"
                >
                  <img v-if="item.img" :src="item.img" class="avatar" />
                  <span v-else class="avatar-uploader-icon">上传图片</span>
                  <i
                    class="el-icon-circle-close"
                    @click.stop="closeImg(index)"
                  ></i>
                </el-upload>
              </div>
              <el-button
                type="danger"
                size="small"
                :disabled="ChangeRadio"
                @click.native="addOptAns"
                >+增加选项与答案</el-button
              >
            </el-checkbox-group>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="解析视频: ">
          <el-input style="width: 400px" v-model="form.VideoURL"> </el-input>
        </el-form-item>
        <!-- 富文本编辑器 -->
        <el-form-item label="答案解析: " prop="answer" class="articles_content">
          <quill-editor
            v-model="form.answer"
            :options="editorOption"
            @blur="$refs.form.validateField('answer')"
          ></quill-editor>
        </el-form-item>
        <el-form-item label="题目备注: ">
          <el-input
            type="textarea"
            v-model="form.remarks"
            style="width: 400px"
          ></el-input>
        </el-form-item>
        <el-form-item label="试题标签: ">
          <el-select
            filterable
            multiple
            v-model="form.tags"
            placeholder="请选择试题标签"
            style="width: 400px"
          >
            <el-option
              v-for="item in tagslist"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button v-if="!form.id" type="primary" @click.native="addquestion"
            >确认提交</el-button
          >
          <el-button v-else type="success" @click.native="addquestion"
            >确认修改</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { add, update, detail } from '@/api/hmmm/questions.js'
// import cos from '@/utils/cos.js'
import { simple as simpless } from '@/api/hmmm/tags.js'
import { simple as simples } from '@/api/hmmm/directorys.js'
import { direction as direct } from '@/api/hmmm/constants.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { list } from '@/api/hmmm/companys.js'
import { simple } from '@/api/hmmm/subjects.js'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
// 引入高亮代码
import hljs from 'highlight.js'
import 'highlight.js/styles/monokai-sublime.css'
var COS = require('cos-js-sdk-v5')
var cos = new COS({
  SecretId: 'AKIDqWzIR0KEtLXfZEg7SinCUaWGnIbrvkJo',
  SecretKey: 'PhmkW4UijV3NTQAfwymKeonaAXfaIo57'
})
export default {
  components: {
    quillEditor
  },
  data () {
    return {
      // 富文本编辑器配置
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
            ['blockquote'], // 引用  代码块
            ['code-block', 'image', 'link'] // 图片、链接
          ],
          // 高亮
          syntax: {
            highlight: text => hljs.highlightAuto(text).value
          }
        },
        placeholder: ''

      },
      radio3: '', // 单选四兄弟选择项
      checkbox: [], // 多选按钮组
      form: {
        // id: 36, // 因为没做基础题库修改才加的id
        subjectID: '', // 学科最终选择的值
        enterpriseID: '', // 企业最终选择的值
        province: '', // 当前选择的市
        city: '', // 当前选择的县
        direction: '', // 当前选择的方向
        catalogID: '', // 当前选择的目录
        question: '', // 题干双向绑定
        answer: '', // 答案解析双向绑定
        tags: '', // 当前选择的试题标签
        VideoURL: '', // 视频上传地址
        questionType: '1', // 题型
        difficulty: '1', // 难度
        remarks: '', // 题目备注
        options: [
          {
            code: 'A', // 代码
            title: '', // 标题
            img: '', // 图片URL
            isRight: true, // 是否正确答案
            num: 0
          },
          {
            code: 'B', // 代码
            title: '', // 标题
            img: '', // 图片URL
            isRight: false, // 是否正确答案
            num: 1
          },
          {
            code: 'C', // 代码
            title: '', // 标题
            img: '', // 图片URL
            isRight: true, // 是否正确答案
            num: 2
          },
          {
            code: 'D', // 代码
            title: '', // 标题
            img: '', // 图片URL
            isRight: false, // 是否正确答案
            num: 3
          }
        ]
      },
      // 校验
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'blur' }],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'blur' }
        ],
        city: [{ required: true, message: '请选择地区', trigger: 'change' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'blur' }],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'blur' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'blur' }
        ],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'blur' }],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [{ required: true, message: '请输入答案解析', trigger: 'blur' }]
      },
      subject: [], // 学科列表
      companylist: [], // 企业列表
      Allcity: [], // 所有的市
      Allcountry: [], // 对应区县
      direction: [], // 所有方向数据
      catalog: [], // 切换学科得到的目录列表
      tagslist: [], // 切换学科得到的试题标签列表  备注: 如果两个值他得到是一个数组, 接口要字符串所以需要转换 例如"11,hadoop" 用toString()
      ChangeRadio: true, // 切换单选组
      ChangeBox: true, // 点击简答隐藏盒子
      number: 0, // 渲染图片使用
      arr: [
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V',
        'W',
        'X',
        'Y',
        'Z'
      ]
    }
  },
  computed: {
    ShowTitle () {
      return this.form.id ? '试题修改' : '试题录入'
    }
  },
  updated () {
    // 这里修改复选框不不变多选的问题
    this.changeradio()
  },
  created () {
    // 调用回显方法
    this.backquestion()
    this.getsimple()
    this.getlist()
    this.getcityData()
    this.direction1()
  },
  methods: {
    // 获取学科列表方法
    async getsimple () {
      const { data } = await simple()
      // console.log(data)
      this.subject = data
    },
    // 获取企业列表方法
    async getlist () {
      const { data } = await list({ pagesize: 999 })
      this.companylist = data.items
    },
    // 获取所有的市
    getcityData () {
      this.Allcity = provinces()
      // console.log(this.Allcity)
    },
    getcountryData () {
      const data = citys(this.form.province)
      // console.log(data)
      this.Allcountry = data
    },
    // 方向数据
    direction1 () {
      this.direction = direct
    },
    // 切换学科获取目录列表和试题标签
    async changeSub () {
      // 目录联动
      this.form.catalogID = ''
      const { data } = await simples({ id: this.form.subjectID })
      this.catalog = data
      console.log(this.catalog)
      // 试题标签联动
      const { data: res } = await simpless({ id: this.form.subjectID })
      // console.log(res)
      this.tagslist = res
    },
    // 单选组切换的事件
    changeradio () {
      // console.log(this.form.questionType)
      if (this.form.questionType === '1') {
        this.ChangeRadio = true
        this.ChangeBox = true
      } else if (this.form.questionType === '2') {
        this.ChangeRadio = false
        this.ChangeBox = true
      } else {
        this.ChangeBox = false
      }
    },
    // 点击增加选项和答案
    addOptAns () {
      const num = ++this.form.options[3].num
      console.log(num)
      this.form.options.push({
        code: this.arr[num], // 代码
        title: '', // 标题
        img: '', // 图片URL
        isRight: false, // 是否正确答案
        num: num
      })
    },
    // 数据回显的方法
    async backquestion () {
      this.form.id = this.$route.query.id // 因为没做基础题库修改只能注释了
      if (!this.form.id) return
      const { data } = await detail({ id: this.form.id })
      // console.log(data)
      this.form = data
    },
    // 点击确定后的方法
    addquestion () {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return
        this.form.tags = this.form.tags.toString()
        if (this.form.id) {
          await update(this.form)
          this.$message.success('修改成功')
        } else {
          await add(this.form)
          this.$message.success('添加成功')
        }
        this.$router.push('/questions/list')
      })
    },
    // 删除图片的方法
    closeImg (index) {
      this.form.options[index].img = ''
    },
    // 为了让对应的图片显示
    ClickImg (index) {
      this.number = index
    },
    // 自定义上传文件配置
    httpRequest ({ file }) {
      const fileobj = this.form.options[this.number]
      if (!file) return
      cos.putObject(
        {
          Bucket: 'xuer-1316265769', // 存储桶的名字
          Region: 'ap-beijing', // 创建存储桶时选择的地域
          Key: +new Date() + file.name, // 表示的是文件在存储桶中的文件名
          Body: file, // 要上传的文件对象
          onProgress: function (progressData) {
            // 可以实时获取咱们上传进度
            // console.log(JSON.stringify(progressData))
          }
        },
        function (err, data) {
          // 上传之后 不管成功还是失败都会执行这个回调
          if (err) {
            this.$message.error('图片上传失败请稍后重试')
            return
          }
          if (data.statusCode === 200) {
            // 表示的当前这个地址的协议呢 会自动使用你网站所使用的协议
            fileobj.img = '//' + data.Location
          }
        }
      )
    }
  }
}
</script>

<style scoped lang='scss'>
.container {
  height: 3000px;
  .card_header {
    margin: 20px 20px 0 20px;
    background-color: #fff;
    border-radius: 3px 3px 0 0;
  }
  .card_body {
    margin: 0 20px;
    border-radius: 0 0 3px 3px;
    ::v-deep .el-textarea__inner {
      height: 96px;
    }
  }
  .articles_content {
    height: 235px;
    .quill-editor {
      height: 235px;
      ::v-deep .ql-toolbar {
        padding: 0;
      }
      ::v-deep .ql-container {
        height: 197px;
      }
    }
  }
  .el_form_itemdf {
    ::v-deep .el-radio-group {
      display: flex;
      flex-direction: column;
      .radio_checked {
        padding-bottom: 20px;
        .el-radio {
          margin: 0;
        }
        .avatar-uploader {
          margin-left: 4px;
          display: inline-block;
          vertical-align: middle;
          margin-bottom: 10px;
        }
        .el-upload {
          border: 1px dashed #d9d9d9;
          border-radius: 6px;
          cursor: pointer;
          position: relative;
          width: 100px;
          height: 60px;
          i {
            position: absolute;
            right: 0;
            top: 0;
            // -webkit-transform: translate(50%, -50%);
            transform: translate(50%, -50%);
            background: #fff;
            font-size: 18px;
            color: #999;
          }
        }
      }
      .avatar-uploader .el-upload:hover {
        border-color: #409eff;
      }
      .avatar-uploader-icon {
        font-size: 14px;
        width: 100px;
        height: 60px;
        line-height: 60px;
        text-align: center;
      }
      .avatar {
        width: 100px;
        height: 60px;
        display: block;
      }
    }
  }
}
</style>
